package com.java.controller;

import com.java.dao.NguoidungDAO;
import com.java.service.ChiTietHDService;
import com.java.service.TheLoai1Service;
import com.java.service.TinhService;
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes({"username"})
public class LoginController {

    private TheLoai1Service tl1Service = new TheLoai1Service();
    private TinhService tinhService = new TinhService();
    private ChiTietHDService cthdService = new ChiTietHDService();
    private NguoidungDAO nguoidung = new NguoidungDAO();

    public void init(ModelMap model) {
        model.addAttribute("TheLoai1", tl1Service.getAll());
        model.addAttribute("Tinh", tinhService.getAll());
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String viewLoginPage(ModelMap model,
    @RequestParam(value = "logon", required = false) boolean logon,
    @RequestParam(value = "active", required = false) boolean active
    ) {
        init(model);
        if(logon)
            model.addAttribute("logon", "true");
        else model.addAttribute("logon", "");
        if(active)
            model.addAttribute("active", "true");
        else model.addAttribute("active", "");
        model.addAttribute("contentpage", "Login.jsp");
        return "User";
    }

    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String loginSuccess(ModelMap model, Principal principal) {
        if (principal == null) {
            return "redirect:/login";
        }

        System.out.println("success");
        init(model);
        String username = principal.getName();
        model.addAttribute("username", nguoidung.findUsername(username));
        //model.addAttribute("contentpage", "index.jsp");
        return "redirect:/";
    }

    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String loginError(ModelMap model, Principal principal) {
        model.addAttribute("error", "true");
        model.addAttribute("contentpage", "Login.jsp");
        return "index";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String Logout(ModelMap model, Principal principal) {
        if (principal == null) {
            return "redirect:/";
        }
        return "redirect:/";
    }
}